package com.example.app.aop;

import com.example.app.annotations.Auth;
import com.example.app.common.ErrorCode;
import com.example.app.common.Role;
import com.example.app.entity.vo.UserVO;
import com.example.app.service.UserService;
import com.example.app.utils.JwtUtils;
import com.example.app.utils.ThrowUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthCheck {

    @Resource
    private UserService userService;

    @Around("@annotation(auth)")
    public Object checkInterceptor(ProceedingJoinPoint joinPoint, Auth auth) throws Throwable {
        //获取必要权限
        Role role = auth.mustRole();
        //获取请求上下文的RequestAttributes对象
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        //从RequestAttributes对象获取HttpServletRequest对象
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        //获取当前登录用户信息
        UserVO loginUserInfo = userService.getLoginUserInfo(request);
        //获取当前登录用户权限
        Integer roleNumber = loginUserInfo.getRole();
        //根据权限数字获取权限枚举
        Role userRole = Role.getRoleByValue(roleNumber);
        //如果用户不是管理员且权限要求管理员
        ThrowUtils.throwIf(!Role.Admin.equals(userRole) && Role.Admin.equals(role), ErrorCode.NO_AUTH_ERROR);
        return joinPoint.proceed();
    }

}
